package com.roc.web.action.windcontroll;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AccountingStatistics;
import com.roc.pojo.Operators;
import com.roc.service.AccountingStatisticsService;
import com.roc.service.IExcelService;
import com.roc.util.Constance;
import com.roc.util.DateUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 占比统计
 * @author 160711BB
 *
 */
@Component
@Scope("prototype")
@Namespace("/windControllSta")
public class AccountingStatisticsAction extends PaginationBaseAction{
	
	private static final long serialVersionUID = 1L;

	private Logger logger=LogManager.getLogger(AccountingStatisticsAction.class);
	
	@Autowired
	private AccountingStatisticsService accountingStatisticsService;
	
	@Autowired
	private IExcelService excelService;
	
	private InputStream excelFile;
	
	private AccountingStatisticsSearchCondition searchCondition;
	
	
	
	@Action(value="accountStaJsp",results={ @Result(name="success",location="/pages/windControllSta/accountStaJsp.jsp")})
	public String accountStaJsp(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		org();
		return SUCCESS;
	}
	
	@Action(value="queryAccountStaList",results={@Result(name="success",location="/pages/windControllSta/accountStaJsp.jsp")})
	public String queryAccountStaList(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		if(searchCondition==null){
			searchCondition=(AccountingStatisticsSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AccountingStatisticsSearchCondition();
			}
		}
		try {
			int rows = accountingStatisticsService.queryAccountStatisticsCount(searchCondition.getStartDate(), searchCondition.getMchtCd(), searchCondition.getEndDate(),searchCondition.getDateFlag());
			List<AccountingStatistics> asList =  new ArrayList<AccountingStatistics>();
			if(rows > 0){
				asList = accountingStatisticsService.queryAccountStatisticsList(searchCondition.getStartDate(), searchCondition.getMchtCd(), searchCondition.getEndDate(),searchCondition.getDateFlag(), calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				for(AccountingStatistics accountingStatistics:asList){
					accountingStatistics.setProvCd(ConfigProperties.gbProviceProperties.get(accountingStatistics.getProvCd()));
					accountingStatistics.setCityCd(ConfigProperties.gbCityProperties.get(accountingStatistics.getCityCd()));
				}
			}
			getRequest().setAttribute("asList", asList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			org();
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
		} catch (Exception e) {
			logger.info("查询占比统计数据异常："+e);
		}
		return SUCCESS;
	}
	
	@Action(value = "exportAccountStaList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/exportAccountStaList.jsp") })
	public String exportAccountStaList(){
		if(searchCondition==null){
			searchCondition=(AccountingStatisticsSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AccountingStatisticsSearchCondition();
			}
		}
		try {
			int rows = accountingStatisticsService.queryAccountStatisticsCount(searchCondition.getStartDate(), searchCondition.getMchtCd(), searchCondition.getEndDate(),searchCondition.getDateFlag());
			List<AccountingStatistics> asList =  new ArrayList<AccountingStatistics>();
			if(rows > 0){
				asList = accountingStatisticsService.queryAccountStatisticsList(searchCondition.getStartDate(), searchCondition.getMchtCd(), searchCondition.getEndDate(),searchCondition.getDateFlag(), calcuStart(getCurrentPage()), rows);
			}
			
			logger.info("rows:" + rows + "    searchRsList.size():"
					+ asList.size());
			
			SXSSFWorkbook work = excelService.exportAccountStaList(asList,searchCondition.getStartDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出占比统计excel结束");
		} catch (Exception e) {
			logger.error("占比统计导出异常:",e);
		}
		return SUCCESS;
	}
	
	public void org(){
		try {
			String yesterday = DateUtil.getDate(new Date(), -1, "yyyyMMdd");
			String today = DateUtil.getDate(new Date(), 0, "yyyyMMdd");
			getRequest().setAttribute("yesterday", yesterday);
			getRequest().setAttribute("today", today);
		} catch (Exception e) {
			logger.error("交易统计页面初始化异常："+e);
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ACCOUNT_STA_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (AccountingStatisticsSearchCondition)getSession().getAttribute(SEARCH_SESSION_ACCOUNT_STA_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public String getExcelName() {
		String excelName = "占比统计" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

	public AccountingStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			AccountingStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	
	
	
}
